package com.raptor.aop.log;


import com.raptor.aop.util.IPUtil;
import com.raptor.base.util.SnowflakeIdWorker;
import com.raptor.base.util.ThreadLocalHolderContext;
import eu.bitwalker.useragentutils.UserAgent;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.Arrays;


@Aspect
@Component
public class LogAspect {


    private static Logger log = LoggerFactory.getLogger(LogAspect.class);


    /**
     * 进入方法时间戳
     */
    private volatile Long startTime;
    /**
     * 方法结束时间戳(计时)
     */
    private volatile Long endTime;


    @Pointcut("@annotation(com.raptor.aop.log.Log)")
    public void annotationPoinCut() {
    }


    /**
     * 前置通知：
     * 1. 在执行目标方法之前执行，比如请求接口之前的登录验证;
     * 2. 在前置通知中设置请求日志信息，如开始时间，请求参数，注解内容等
     *
     * @param joinPoint
     * @throws Throwable
     */
    @Before("annotationPoinCut()")
    public void doBefore(JoinPoint joinPoint) {
        // 接收到请求，记录请求内容
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        //获取请求头中的User-Agent
        UserAgent userAgent = UserAgent.parseUserAgentString(request.getHeader("User-Agent"));
        //打印请求的内容
        startTime = System.currentTimeMillis();
        String id = String.valueOf(SnowflakeIdWorker.getInstance().nextId());
        ThreadLocalHolderContext.setContext(id);
        log.info("请求id：" + id);
        log.info("请求开始时间：" + LocalDateTime.now());
        log.info("请求Url : " + request.getRequestURL().toString());
        log.info("请求方式 : " + request.getMethod());
        log.info("请求ip : " + IPUtil.getIpAddress(request));
        log.info("请求方法 : " + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
        String parameter = Arrays.toString(joinPoint.getArgs());
        log.info("请求参数 : " + parameter);
        // 系统信息
        log.info("浏览器：", userAgent.getBrowser().toString());
        log.info("浏览器版本：", userAgent.getBrowserVersion());
        log.info("操作系统: ", userAgent.getOperatingSystem().toString());
    }


    @After("annotationPoinCut()")
    public void doAfterReturn() {
        endTime = System.currentTimeMillis();
        log.info("请求结束时间：" + LocalDateTime.now());
        log.info("请求耗时：" + (endTime - startTime));
    }


    /**
     * 返回通知：
     * 1. 在目标方法正常结束之后执行
     * 1. 在返回通知中补充请求日志信息，如返回时间，方法耗时，返回值，并且保存日志信息
     *
     * @param ret
     * @throws Throwable
     */
    @AfterReturning(returning = "ret", pointcut = "annotationPoinCut()")
    public void doAfterReturning(Object ret) throws Throwable {
        endTime = System.currentTimeMillis();
        log.info("请求id：" + ThreadLocalHolderContext.getContext());
        log.info("请求结束时间：" + LocalDateTime.now());
        log.info("请求耗时：" + (endTime - startTime));
    }

    /**
     * 异常通知：
     * 1. 在目标方法非正常结束，发生异常或者抛出异常时执行
     * 1. 在异常通知中设置异常信息，并将其保存
     *
     * @param throwable
     */
    @AfterThrowing(value = "annotationPoinCut()", throwing = "throwable")
    public void doAfterThrowing(Throwable throwable) {
        // 保存异常日志记录
        log.info("请求id：" + ThreadLocalHolderContext.getContext());
        log.error("发生异常时间：" + LocalDateTime.now());
        log.error("抛出异常：", throwable);
    }
}
